<template>
    <view class="orderDetail">
        <view class="search_top_back">
            <view v-if="orderDetail.status == 10" class="time">
                <view class="time1"> <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/time.png" mode=""></image>等待买家付款 </view>
                <view class="timedate">
                    剩余付款时间：{{ day > 0 ? day + '天' : '' }}{{ hr != '00' ? hr + '小时' : '' }}{{ min }}分钟{{
                        sec
                    }}秒
                </view>
            </view>
            <view v-if="orderDetail.status == 20" class="time">
                <view class="time1">
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/time1.png" mode=""></image>买家已付款，等待卖家发货
                </view>
            </view>
            <view v-if="orderDetail.status == 30" class="time">
                <view class="time1">
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/time2.png" mode=""></image>卖家已发货，等待买家收货
                </view>
            </view>
            <view v-if="orderDetail.status == 40" class="time">
                <view class="time1"> <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/time3.png" mode=""></image>交易完成 </view>
            </view>
            <view v-if="orderDetail.status == 60" class="time">
                <view class="time1"> <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/time4.png" mode=""></image>交易已取消 </view>
            </view>
            <view v-if="orderDetail.status == 50" class="time">
                <view class="time1"> <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/time4.png" mode=""></image>交易已取消 </view>
            </view>
        </view>

        <view v-if="orderDetail.typeId == 0" class="address-main" style="margin: -24rpx auto 0; width: 100%">
            <view class="address-left">
                <view>
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/address.png" mode=""></image>
                </view>
                <view class="address-title">
                    <view class="address-name"
                        >{{ orderDetail.receiver }}<text>{{ orderDetail.contactNumber }}</text>
                    </view>
                    <view class="address_title">地址：{{ orderDetail.receiverAddress }}</view>
                </view>
            </view>
        </view>

        <view
            v-if="(orderDetail.status == 30 || orderDetail.status == 40) && orderDetail.typeId == 1"
            class="address-main"
            style="margin: -24rpx auto 0; width: 100%"
        >
            <view class="address-left">
                <view>
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/mall/sao.png" mode=""></image>
                </view>
                <view class="address-title"
                    ><text style="font-size: 24rpx; color: #666; font-weight: 300">核销码</text>
                    <view style="max-height: 120rpx; overflow-y: auto">
                        <view
                            v-for="(hxItem, hxIndex) in orderDetail.writeOffDataList"
                            :key="hxIndex"
                            class="address_title"
                            style="font-weight: 600; font-size: 28rpx; line-height: 40rpx; color: #333"
                        >
                            {{ hxItem.writeOffCode }}<span v-if="hxItem.status == 1" style="color: #666">已核销</span
                            ><text
                                @click="copyEventHX(hxItem)"
                                style="
                                    width: 66rpx;
                                    display: inline-block;
                                    height: 32rpx;
                                    text-align: center;
                                    line-height: 32rpx;
                                    font-size: 20rpx;
                                    background-color: #e6e6e6;
                                    color: #333;
                                    margin-left: 10rpx;
                                    border-radius: 20rpx;
                                "
                                >复制</text
                            >
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <view class="orderlist-main" style="margin-top: 20rpx; width: 100%">
            <view class="orderlist-item" style="width: 100%">
                <view class="orderlist-content">
                    <view class="orderlist-icon">
                        <image style="background-color: #eaeaea" :src="orderDetail.skuPicAbsolute" mode=""></image>
                    </view>
                    <view class="orderlist-right">
                        <view class="orderlist-right-title">{{ orderDetail.goodsName }}</view>
                        <view class="orderlist-right-tag">{{ getSkuString() }}</view>
                        <view class="orderlist-right-price">
                            <view>¥{{ orderDetail.unitPrice }}</view>
                            <view> *{{ orderDetail.number }}</view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <view class="orderDetail-type">
            <view class="orderDetail-type_item">
                <view>商品金额</view>
                <view>¥{{ orderDetail.goodsPrice }}</view>
            </view>
            <view class="orderDetail-type_item">
                <view>运费</view>
                <view>¥0.00</view>
            </view>
            <view class="orderDetail-type_item">
                <view>合计</view>
                <view>¥{{ orderDetail.totalPrice }}</view>
            </view>
            <view style="width: 100%; height: 1px; background-color: #e6e6e6"></view>
            <view class="orderDetail-type_item" style="padding-top: 30rpx">
                <view>等级折扣</view>
                <view>-¥{{ orderDetail.gradeDiscountAmount }}</view>
            </view>
            <view class="orderDetail-type_item">
                <view>积分抵扣</view>
                <view>-¥{{ orderDetail.deductionOfPoints }}</view>
            </view>
            <view class="orderDetail-type_item" v-if="orderDetail.discountAmount">
                <view>优惠券</view>
                <view>-¥{{ orderDetail.discountAmount.toFixed(2) }}</view>
            </view>
            <view class="orderDetail-type_item">
                <view>应付款</view>
                <view style="color: #ff413b">¥{{ orderDetail.amount }}</view>
            </view>
        </view>

        <view class="orderDetail-type">
            <view class="orderDetail-type_item">
                <view>订单编号</view>
                <view>{{ orderDetail.orderId }}<text @click="copyEvent">复制</text></view>
            </view>
            <view class="orderDetail-type_item">
                <view>下单时间</view>
                <view>{{ orderDetail.orderAddTime }}</view>
            </view>
            <view
                v-if="orderDetail.status == 20 || orderDetail.status == 30 || orderDetail.status == 40"
                class="orderDetail-type_item"
            >
                <view>付款时间</view>
                <view>{{ orderDetail.paymentTime }}</view>
            </view>
            <view v-if="orderDetail.status == 30 || orderDetail.status == 40" class="orderDetail-type_item">
                <view>发货时间</view>
                <view>{{ orderDetail.typeId == 1 ? orderDetail.paymentTime : orderDetail.deliveryGoodsTime }}</view>
            </view>
            <view v-if="orderDetail.status == 40" class="orderDetail-type_item">
                <view>收货时间</view>

                <view>{{ orderDetail.receiverGoodsTime }}</view>
            </view>
            <view v-if="orderDetail.status == 60 || orderDetail.status == 50" class="orderDetail-type_item">
                <view>取消时间</view>
                <view>{{ orderDetail.cancelTime }}</view>
            </view>
            <view v-if="orderDetail.status == 60 || orderDetail.status == 50" class="orderDetail-type_item">
                <view>取消原因</view>
                <view>{{ orderDetail.cancelReason }}</view>
            </view>
            <view v-if="orderDetail.status != 60 && orderDetail.status != 50" class="orderDetail-type_item">
                <view style="width: 110rpx">订单备注</view>
                <view
                    style="
                        width: calc(100% - 200rpx);
                        line-height: 36rpx;
                        white-space: pre-line;
                        word-break: break-all;
                        word-wrap: break-word;
                        text-align: right;
                    "
                >
                    {{ orderDetail.remark }}
                </view>
            </view>
        </view>
        <view v-if="orderDetail.status != 20" class="gap_view"></view>
        <view v-if="orderDetail.status != 20" class="footer_order">
            <view class="menu_footer_btn" v-if="orderDetail.status == 10">
                <view @click="payEvent" style="margin-right: 30rpx" class="footer_active_btn">去付款</view>
                <view @click="cancelOrder" style="margin-right: 20rpx" class="footer_normal_btn">取消订单</view>
            </view>
            <view class="menu_footer_btn" v-if="orderDetail.status == 40 && orderDetail.typeId == 0">
                <view @click="goToExpress" style="margin-right: 30rpx" class="footer_normal_btn">物流信息</view>
                <view @click="deleteOrder" style="margin-right: 20rpx" class="footer_normal_btn">删除订单</view>
            </view>
            <view class="menu_footer_btn" v-if="orderDetail.status == 40 && orderDetail.typeId == 1">
                <view @click="deleteOrder" style="margin-right: 30rpx" class="footer_normal_btn">删除订单</view>
            </view>
            <view class="menu_footer_btn" v-if="orderDetail.status == 30 && orderDetail.typeId == 0">
                <view @click="confirmrReceipt" style="margin-right: 30rpx" class="footer_active_btn">确认收货</view>
                <view @click="goToExpress" style="margin-right: 20rpx" class="footer_normal_btn">物流信息</view>
            </view>
            <view class="menu_footer_btn" v-if="orderDetail.status == 30 && orderDetail.typeId == 1">
                <view @click="confirmrReceipt" style="margin-right: 30rpx" class="footer_active_btn">确认收货</view>
            </view>
            <view class="menu_footer_btn" v-if="orderDetail.status == 50 || orderDetail.status == 60">
                <view @click="deleteOrder" style="margin-right: 30rpx" class="footer_normal_btn">删除订单</view>
            </view>
        </view>
    </view>
</template>

<script>
var statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
export default {
    data() {
        return {
            statusBarHeight: statusBarHeight,
            Type: 1,
            id: '',
            orderDetail: {},
            day: 0,
            hr: '00',
            min: '00',
            sec: '00',
            loading: false,
            timer: null,
        };
    },
    methods: {
        countdown() {
            const end = new Date(this.orderDetail.paymentTimeEnd.replace(/-/g, '/')).getTime();
            const now = new Date().getTime();
            const msec = end - now;
            if (msec <= 0) {
                this.day = 0;
                this.requestOrderDetail();
                return;
            }
            let day = parseInt(msec / 1000 / 60 / 60 / 24);
            let hr = parseInt((msec / 1000 / 60 / 60) % 24);
            let min = parseInt((msec / 1000 / 60) % 60);
            let sec = parseInt((msec / 1000) % 60);
            this.day = day;
            this.hr = hr > 9 ? hr : '0' + hr;
            this.min = min > 9 ? min : '0' + min;
            this.sec = sec > 9 ? sec : '0' + sec;
            const that = this;

            if (min >= 0 && sec >= 0) {
                if (min == 0 && sec == 0 && day == 0 && hr == 0) {
                    if (this.orderDetail.status == 10) {
                        this.closeOrder();
                        return;
                    }
                }
                this.timer = setTimeout(function () {
                    that.countdown();
                }, 1000);
            }
        },
        getSkuString() {
            var skuString = '';
            if (this.orderDetail.specsDataList) {
                this.orderDetail.specsDataList.forEach((item) => {
                    if (skuString == '') {
                        skuString = item.specsName + ':' + (item.childs.length > 0 ? item.childs[0].specsName : '');
                    } else {
                        skuString =
                            skuString +
                            ',' +
                            item.specsName +
                            ':' +
                            (item.childs.length > 0 ? item.childs[0].specsName : '');
                    }
                });
                return skuString;
            }
        },
        tabType(e) {
            this.Type = e;
        },
        back() {
            uni.navigateBack();
        },
        closeOrder() {
            this.request
                .httpTokenRequest(`/mp-api/wx/order/close/${this.orderDetail.id}`, null, 'POST', false)
                .then((res) => {
                    if (res.code == 0) {
                        // this.requestOrderDetail()
                        uni.redirectTo({
                            url: `/packageOrder/pages/orderlist/orderDetail?id=${this.orderDetail.id}`,
                        });
                    }
                });
        },
        copyEvent() {
            uni.setClipboardData({
                data: this.orderDetail.orderId,
                success: function () {
                    uni.showToast({
                        icon: 'none',
                        title: '复制成功',
                    });
                },
            });
        },
        copyEventHX(hxItem) {
            uni.setClipboardData({
                data: hxItem.writeOffCode,
                success: function () {
                    uni.showToast({
                        icon: 'none',
                        title: '复制成功',
                    });
                },
            });
        },
        payEvent() {
            if (this.loading) {
                return;
            }
            var form = {
                id: this.orderDetail.id,
            };
            const that = this;
            that.loading = true;
            this.request
                .httpTokenJsonRequest('/mp-api/wx/order/payment', form, 'POST', false)
                .then((res) => {
                    if (res.code == 0) {
                        uni.requestPayment({
                            provider: 'wxpay',
                            timeStamp: res.data.timeStamp,
                            nonceStr: res.data.nonceStr,
                            package: res.data.packageValue,
                            signType: res.data.signType,
                            paySign: res.data.paySign,
                            success: (payRes) => {
                                this.requestOrderDetail();
                                this.subscribeMessage();
                            },
                            fail: (err) => {
                                that.loading = false;
                                uni.showToast({
                                    title: '支付失败',
                                });
                            },
                        });
                    } else {
                        that.loading = false;
                    }
                })
                .catch((err) => {
                    that.loading = false;
                });
        },
        subscribeMessage() {
            uni.requestSubscribeMessage({
                tmplIds: [
                    '4WlKLcNqWHQxN6WYburUGD8GdmGg7IcRmDg0x3u_Rds',
                    'OB01OzknOemOioXmf-SzbogLAC8FjjFhRuxKxLX7uUM',
                    'xX3kwdzC5I-61OxI_yUIGhO_BozN7a8U-PVGjORIlJU',
                ],
                success(res) {},
            });
        },
        cancelOrder() {
            uni.showModal({
                cancelText: '取消',
                confirmText: '确定',
                title: '是否确认取消此订单？',
                success: (res) => {
                    if (res.confirm) {
                        this.request
                            .httpTokenRequest(`/mp-api/wx/order/cancel/${this.orderDetail.id}`, null, 'POST', false)
                            .then((res) => {
                                if (res.code == 0) {
                                    this.requestOrderDetail();
                                }
                            });
                    }
                },
            });
        },
        deleteOrder() {
            uni.showModal({
                cancelText: '取消',
                confirmText: '确定',
                title: '是否确认删除此订单？',
                success: (res) => {
                    if (res.confirm) {
                        this.request
                            .httpTokenRequest(`/mp-api/wx/order/delete/${this.orderDetail.id}`, null, 'POST', false)
                            .then((res) => {
                                if (res.code == 0) {
                                    uni.navigateBack();
                                }
                            });
                    }
                },
            });
        },
        goToExpress() {
            uni.navigateTo({
                url: `/packageMine/pages/logistics/logistics?id=${this.orderDetail.id}`,
            });
        },
        confirmrReceipt() {
            uni.showModal({
                cancelText: '取消',
                confirmText: '确定',
                title: '是否确认已收货？',
                success: (res) => {
                    if (res.confirm) {
                        this.request
                            .httpTokenRequest(`/mp-api/wx/order/confirm/${this.orderDetail.id}`, null, 'POST', false)
                            .then((res) => {
                                if (res.code == 0) {
                                    this.requestOrderDetail();
                                }
                            });
                    }
                },
            });
        },
        requestOrderDetail() {
            this.request.httpTokenRequest(`/mp-api/wx/order/details/${this.id}`, null, 'POST', false).then((res) => {
                if (res.code == 0) {
                    this.orderDetail = res.data;
                    if (res.data.status === 10) {
                        const end = new Date(res.data.paymentTimeEnd.replace(/-/g, '/')).getTime();
                        const now = new Date().getTime();
                        const msec = end - now;
                        // 当订单状态为10且最后支付时间超过当前时间时，无需调用倒计时，直接取消订单
                        if (msec <= 0) {
                            this.closeOrder();
                        } else {
                            this.countdown();
                        }
                    }
                }
            });
        },
    },
    onLoad(option) {
        if (option.id) {
            this.id = option.id;
            this.requestOrderDetail();
        }
    },
    onUnload() {
        clearTimeout(this.timer);
        this.timer = null;
    },
};
</script>

<style scoped>
.search_top_back {
    background-color: #44b794;
    width: 100%;
    height: 145rpx;
    display: flex;
    flex-direction: column;
}

.gap_view {
    width: 100%;
    height: calc(128rpx + env(safe-area-inset-bottom));
}

.footer_order {
    height: calc(96rpx + env(safe-area-inset-bottom));
    width: 100%;
    background-color: #ffffff;
    box-shadow: 0rpx -1rpx 0rpx 0rpx #e6e6e6;
    position: fixed;
    z-index: 999;
    left: 0;
    bottom: 0;
}

.footer_normal_btn {
    width: 160rpx;
    height: 64rpx;
    border-radius: 32rpx;
    border: 1rpx solid #cccccc;
    color: #666666;
    font-size: 24rpx;
    text-align: center;
    line-height: 64rpx;
    margin-top: 20rpx;
}

.footer_active_btn {
    width: 160rpx;
    height: 64rpx;
    background: linear-gradient(180deg, #ffad77 0%, #ff822e 100%);
    border-radius: 32rpx;
    color: #ffffff;
    font-size: 26rpx;
    text-align: center;
    line-height: 64rpx;
    margin-top: 20rpx;
}

.menu_footer_btn {
    display: flex;
    flex-direction: row-reverse;
}
</style>
